/* Server.cpp */

#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>

#include "safeproxy.h"
#include "Server.h"

//-----------------------------------------------------------------------------
// Constructor
Server::Server() {
}

//-----------------------------------------------------------------------------
// Deconstructor.
Server::~Server() {

}

//-----------------------------------------------------------------------------
// Listen on the specified port.  Adding the socket to our event list.  
// Return true if we succeeded in listening to the socket.
bool Server::Listen(const int port) {
	struct sockaddr_in sin;
	int on = 1;
	
	// will not work with a 0 or a negative number
	ASSERT(port > 0);
	
	ASSERT(_socket == 0);
	
	// CJW: Create the socket place holder
	_socket = socket(AF_INET, SOCK_STREAM, 0);
	if (_socket > 0) {
	
		if ( setsockopt(_socket, SOL_SOCKET, SO_REUSEADDR, (const char*) &on, sizeof (on)) == -1) {
			close(_socket);
			_socket = 0;
		}
		else {
	
			sin.sin_family = AF_INET;
			sin.sin_port = htons(port);
			sin.sin_addr.s_addr = INADDR_ANY;

			if (bind(_socket, (struct sockaddr *) &sin, sizeof(struct sockaddr)) == 0) {
				// Can be in new thread
				if (listen(_socket, 5) != 0) {
					close(_socket);
					_socket = 0;
				}
				else {
					// Add an event.
					event_set(&_event, _socket, EV_READ, EventRun, this);
					event_add(&_event, NULL);
				}
			}
			else {
				_socket = 0;
			}
		}
	}
	
	return (_socket);
}
